package com.ctgu.chatapp.Netty.Handler

import com.ctgu.chatapp.Netty.protocol.Message.Heartbeat
import com.ctgu.chatapp.utils.MessageUtils
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import java.util.concurrent.TimeUnit

class Ping : SimpleChannelInboundHandler<Heartbeat?>() {

    private lateinit var channel: Channel

    @Throws(Exception::class)
    override fun channelActive(ctx: ChannelHandlerContext) {
        super.channelActive(ctx)
        this.channel = ctx.channel()
        ping(ctx.channel())
    }

    private fun ping(channel: Channel) {
        val base = 8
        val future = channel.eventLoop().schedule(
            {
                if (channel.isActive) {
                    println("发送心跳包")
                    channel.writeAndFlush(MessageUtils.getHeartBeat())
                } else {
                    channel.closeFuture()
                    throw RuntimeException()
                }
            }, base.toLong(), TimeUnit.SECONDS
        )
        future.addListener {
            if (it.isSuccess) {
                ping(channel)
            }
        }
    }

    @Throws(Exception::class)
    override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) {
        // 当Channel已经断开的情况下, 仍然发送数据, 会抛异常, 该方法会被调用.
        cause.printStackTrace()
        ctx.close()
    }

    @Throws(Exception::class)
    override fun messageReceived(ctx: ChannelHandlerContext, msg: Heartbeat?) {
    }
}